<?php 
/**
 * 揭晓商品中奖者
 */
class Tocode {

	private $go_list;//前100个夺宝订单记录
	public $go_code;//揭晓幸运码
	public $go_content;
	public $cyrs;
	public $shop;//当前揭晓商品
	public $count_time='';//总100条记录时间之和
	
	
	public function __construct($db) {
		$this->db = $db;
	}	

	public function config($shop=null,$type=null){
		$this->shop = $shop;		
	}
	
	public function get_run_tocode(){
		
	}
	
	public function returns(){
	
	
	}
	
	/**
         * 
         * @param type $time 截止当前夺宝记录时间
         * @param type $num 累加夺宝记录数量
         * @param type $cyrs 商品参与总人数
         * @return boolean
         */
	public function run_tocode(&$time='',$num=100,$cyrs='233'){
		if(empty($time))return false;
		if(empty($num))return false;
		if(empty($cyrs))return false;
		$this->times = $time;
		$this->num = $num;
		$this->cyrs = $cyrs;
		$this->get_code_user_html();
		//$this->get_user_go_code();
	}
        
	private function get_code_dabai(){
		$go_list = $this->go_list;
		$html=array();
		$count_time = 0;
		foreach($go_list as $key=>$v){
			$html[$key]['time'] = $v['time'];	
			$html[$key]['username'] = $v['username'];	
			$html[$key]['uid'] = $v['uid'];
			$html[$key]['shopid'] = $v['shopid'];	
			$html[$key]['shopname'] = $v['shopname'];	
			$html[$key]['shopqishu'] = $v['shopqishu'];
			$html[$key]['gonumber'] = $v['gonumber'];			
			$h=abs(date("H",$v['time']));
			$i=date("i",$v['time']);
			$s=date("s",$v['time']);	
			list($time,$ms) = explode(".",$v['time']);
			$time = $h.$i.$s.$ms;
			$html[$key]['time_add'] = $time;
			$count_time += $time;			
		}
		$this->go_content = serialize($html);//100条云购记录
		$this->count_time = $count_time;//时间总和
		$this->go_code = 10000001+fmod($count_time,$this->cyrs);//取余数，并计算最终幸运码			
	}
	
	private function get_code_yibai(){		
		$time = $this->times;
		$cyrs = $this->cyrs;		
		$h=abs(date("H",$time));
		$i=date("i",$time);
		$s=date("s",$time);		
		$w=substr($time,11,3);
		$num= $h.$i.$s.$w;
		if(!$cyrs)$cyrs=1;
		$this->go_code = 10000001+fmod($num*100,$cyrs);
		$this->go_content = false;
	}
	//制定中奖人
	private function get_user_go_code(){
		//指定中奖人
		if(file_exists(G_SYSTEM.'modules/goodspecify/lib/'.'itocode.class.php')):
			$itocode = System::load_app_class("itocode","goodspecify");
			$itocode->go_itocode($this->shop,$this->go_code,$this->go_content,$this->count_time);
		endif;
		$this->get_code_user_html();
	}
		
	private function get_code_user_html(){		
		$time = $this->times;
		$num  = $this->num;
                //获取指定在$time时间之前指定数量$num条夺宝记录
		$this->go_list = $this->db->select("*")->from("tan_go_member_go_record")->where(array("time <"=>$time))->order_by("id DESC")->limit($num,0)->get()->result_array();
		if($this->go_list  && count($this->go_list) >= $this->num){//如果结果数量大于或等于100
			$this->get_code_dabai();
		}else{//小于100
			$this->get_code_yibai();
		}
	}
	
}